package cn.hetra.hj212.core;

import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageCodec;

import java.io.StringReader;
import java.util.List;

public class HJ212Codec  extends MessageToMessageCodec<String,HJ212Data> {

    public static long crc16Checksum(char[]puchMsg)
    {
        long crc_reg, check;
        crc_reg = 0xFFFF;
        for (char i : puchMsg) {
            crc_reg = (crc_reg >> 8) ^ i;
            for (long j = 0; j < 8; j++) {
                check = crc_reg & 0x0001;
                crc_reg >>= 1;
                if (check == 0x0001) {
                    crc_reg ^= 0xA001;
                }
            }
        }
        return crc_reg;
    }
    @Override
    protected void encode(ChannelHandlerContext ctx, HJ212Data msg, List<Object> out) throws Exception {
        String datastr =  msg.getData();
        long jisuan_crc16 =crc16Checksum(datastr.toCharArray());
        String data = String.format("##%04d%s%04X\r\n",datastr.length(),datastr,jisuan_crc16);
        out.add(data);
    }

    @Override
    protected void decode(ChannelHandlerContext ctx, String msg, List<Object> out) throws Exception {
        StringReader stringReader = new StringReader(msg);
        char[] head = new char[2];
        stringReader.read(head);
        if("##".equals(new String(head))){
            char[] dataLength = new char[4];
            stringReader.read(dataLength);
            char[] data = new char[Integer.valueOf(new String(dataLength))];
            stringReader.read(data);
            char[] crc = new char[4];
            stringReader.read(crc);
            long l = crc16Checksum(data);
            HJ212Data item = new HJ212Data.Parser(new String(data));
            if(Integer.valueOf(new String(crc),16)!=l){
                //CRC校验失败
                ctx.close();
            }
            out.add(item);
        }
    }
}
